// 公共基础模块
// 全局变量
let currentPage = 'dashboard';
let globalConfig = {
    apiBase: '/evaluation/api/admin',
    pageSize: 10
};
let userInfo = null; // 存储用户信息

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 应用初始化
function initializeApp() {
    checkLogin();
    setupGlobalErrorHandler();
    startHeartbeat();
    setupVisibilityChangeHandler();
    setupModalEvents();
    initializeModules();
}

// 初始化各个模块
function initializeModules() {
    // 等待所有模块文件加载完成后初始化
    if (typeof DashboardModule !== 'undefined') {
        DashboardModule.init();
    }
    if (typeof BaseInfoModule !== 'undefined') {
        BaseInfoModule.init();
    }
}

// 设置页面可见性变化处理
function setupVisibilityChangeHandler() {
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden) {
            setTimeout(function() {
                checkLoginHeartbeat();
            }, 1000);
        }
    });
}

// 启动心跳检测
function startHeartbeat() {
    setInterval(function() {
        checkLoginHeartbeat();
    }, 5 * 60 * 1000);
}

// 心跳检测登录状态
function checkLoginHeartbeat() {
    fetch(globalConfig.apiBase + '/check')
        .then(response => response.json())
        .then(data => {
            if (!data.success || data.code !== 200) {
                handleUnauthorized();
            }
        })
        .catch(error => {
            console.warn('心跳检测失败:', error);
        });
}

// 设置全局错误处理器
function setupGlobalErrorHandler() {
    const originalFetch = window.fetch;
    window.fetch = function(...args) {
        return originalFetch.apply(this, args)
            .then(response => {
                if (response.status === 401) {
                    handleUnauthorized();
                    return Promise.reject(new Error('Unauthorized'));
                } else if (response.status === 403) {
                    showAlert('权限不足，无法访问该功能', 'warning');
                    return Promise.reject(new Error('Forbidden'));
                }
                return response;
            })
            .catch(error => {
                if (error.message === 'Unauthorized' || error.message === 'Forbidden') {
                    throw error;
                }
                console.error('API请求错误:', error);
                throw error;
            });
    };
}

// 处理未授权错误
function handleUnauthorized() {
    console.log('检测到未授权访问，重定向到登录页面');
    localStorage.removeItem('adminLogin');
    localStorage.removeItem('adminUser');
    redirectToLogin('登录状态已过期，请重新登录');
}

// 检查登录状态
function checkLogin() {
    fetch(globalConfig.apiBase + '/check')
        .then(response => response.json())
        .then(data => {
            if (!data.success || data.code !== 200) {
                localStorage.removeItem('adminLogin');
                localStorage.removeItem('adminUser');
                redirectToLogin('登录状态已过期，请重新登录');
                return;
            }
            
            // 保存用户信息
            userInfo = data.data;
            
            // 更新用户显示名称
            if (userInfo && userInfo.userName) {
                document.getElementById('username').textContent = userInfo.userName + ' (' + userInfo.userRole + ')';
            }
            
            // 根据用户权限设置菜单显示
            setupMenuByPermission();
        })
        .catch(error => {
            console.error('检查登录状态失败:', error);
            localStorage.removeItem('adminLogin');
            localStorage.removeItem('adminUser');
            redirectToLogin('网络连接异常，请重新登录');
        });
}

// 根据用户权限设置菜单显示
function setupMenuByPermission() {
    console.log('setupMenuByPermission called, userInfo:', userInfo);
    
    if (!userInfo) {
        console.log('userInfo is null, returning');
        return;
    }
    
    // 如果是校领导（userType = '1'），只显示特定菜单
    if (userInfo.userType === '1') {
        console.log('User is school leader, hiding admin menus');
        // 隐藏管理员专用菜单
        hideAdminOnlyMenus();
        // 显示校领导可访问的菜单
        showSchoolLeaderMenus();
        // 控制快速访问功能
        hideAdminQuickActions();
    } else {
        console.log('User is admin, showing all menus');
        // 管理员显示所有菜单和快速访问
        showAllMenus();
        showAllQuickActions();
    }
}

// 隐藏管理员专用菜单
function hideAdminOnlyMenus() {
    console.log('hideAdminOnlyMenus called');
    
    // 隐藏基础信息管理整个分组
    const menuGroups = document.querySelectorAll('.menu-group');
    console.log('Found menu groups:', menuGroups.length);
    
    if (menuGroups.length >= 2) {
        // 隐藏第二个菜单组（基础信息管理）
        menuGroups[1].style.display = 'none';
        console.log('Hidden menu group 1 (基础信息管理)');
    }
    
    // 隐藏测评内容管理中的部分菜单项
    const allMenuItems = document.querySelectorAll('.menu-item');
    console.log('Found menu items:', allMenuItems.length);
    
    allMenuItems.forEach((menuItem, index) => {
        const onclickAttr = menuItem.getAttribute('onclick');
        if (onclickAttr) {
            if (onclickAttr.includes('evaluation-content-management') || 
                onclickAttr.includes('evaluation-type-management')) {
                menuItem.style.display = 'none';
                console.log('Hidden menu item:', onclickAttr);
            }
        }
    });
}

// 显示校领导可访问的菜单
function showSchoolLeaderMenus() {
    console.log('showSchoolLeaderMenus called');
    
    // 确保这些菜单可见
    const allowedMenus = [
        'dashboard',
        'evaluation-relation-management', 
        'evaluation-score-management'
    ];
    
    allowedMenus.forEach(menuId => {
        const menuItem = document.querySelector(`[onclick*="${menuId}"]`);
        if (menuItem && menuItem.classList.contains('menu-item')) {
            menuItem.style.display = 'block';
            console.log('Shown menu item:', menuId);
        }
    });
    
    // 强制隐藏不允许的菜单项
    const allMenuItems = document.querySelectorAll('.menu-item');
    allMenuItems.forEach(menuItem => {
        const onclickAttr = menuItem.getAttribute('onclick');
        if (onclickAttr) {
            const isAllowed = allowedMenus.some(allowedMenu => onclickAttr.includes(allowedMenu));
            if (!isAllowed) {
                menuItem.style.display = 'none';
            }
        }
    });
    
    // 隐藏测评分数页面中的分数计算tab
    setTimeout(() => {
        hideCalculationTabForSchoolLeader();
        hideRelationGenerationForSchoolLeader();
    }, 500);
}

// 为校领导隐藏分数计算功能
function hideCalculationTabForSchoolLeader() {
    console.log('hideCalculationTabForSchoolLeader called');
    
    // 隐藏分数计算tab
    const calculationTab = document.querySelector('#evaluation-score-management .tab[onclick*="calculation"]');
    if (calculationTab) {
        calculationTab.style.display = 'none';
        console.log('Hidden calculation tab for school leader');
    }
    
    // 隐藏分数计算tab内容
    const calculationTabContent = document.getElementById('calculation-tab');
    if (calculationTabContent) {
        calculationTabContent.style.display = 'none';
        console.log('Hidden calculation tab content for school leader');
    }
}

// 为校领导隐藏测评关系生成功能
function hideRelationGenerationForSchoolLeader() {
    console.log('hideRelationGenerationForSchoolLeader called');
    
    // 隐藏整个测评关系生成区域
    const generationSection = document.getElementById('relation-generation-section');
    if (generationSection) {
        generationSection.style.display = 'none';
        console.log('Hidden relation generation section for school leader');
    }
    
    // 备用方案：分别隐藏部门和教师测评关系生成
    const deptGeneration = document.getElementById('dept-relation-generation');
    if (deptGeneration) {
        deptGeneration.style.display = 'none';
        console.log('Hidden dept relation generation for school leader');
    }
    
    const teacherGeneration = document.getElementById('teacher-relation-generation');
    if (teacherGeneration) {
        teacherGeneration.style.display = 'none';
        console.log('Hidden teacher relation generation for school leader');
    }
}

// 隐藏管理员专用的快速访问功能
function hideAdminQuickActions() {
    console.log('hideAdminQuickActions called');
    
    // 隐藏教师管理快速访问
    const teacherManagementAction = document.querySelector('.action-button[onclick*="teacher-info-management"]');
    if (teacherManagementAction) {
        teacherManagementAction.style.display = 'none';
        console.log('Hidden teacher management quick action');
    }
    
    // 隐藏数据导出快速访问
    const dataExportAction = document.querySelector('.action-button[onclick*="data-export"]');
    if (dataExportAction) {
        dataExportAction.style.display = 'none';
        console.log('Hidden data export quick action');
    }
}

// 显示所有快速访问功能（管理员权限）
function showAllQuickActions() {
    console.log('showAllQuickActions called');
    
    // 显示所有快速访问按钮
    document.querySelectorAll('.action-button').forEach(action => {
        action.style.display = 'block';
    });
}

// 跳转到登录页面
function redirectToLogin(message) {
    if (message) {
        sessionStorage.setItem('loginMessage', message);
    }
    window.location.href = 'login.html';
}

// 退出登录
function logout() {
    fetch(globalConfig.apiBase + '/logout', {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        localStorage.removeItem('adminLogin');
        localStorage.removeItem('adminUser');
        redirectToLogin('已成功退出登录');
    })
    .catch(error => {
        console.error('退出登录失败:', error);
        localStorage.removeItem('adminLogin');
        localStorage.removeItem('adminUser');
        redirectToLogin('退出登录');
    });
}

// 模态框管理
function setupModalEvents() {
    const modal = document.getElementById('commonModal');
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });
    }
}

// 显示模态框
function showModal(title, content) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = content;
    document.getElementById('commonModal').classList.add('show');
}

// 关闭模态框
function closeModal() {
    document.getElementById('commonModal').classList.remove('show');
}

// 内容区域切换 - 已移至index.html中重新实现以支持组件化
// function showContent(contentId) {
//     // 隐藏所有内容区域
//     document.querySelectorAll('.content-area').forEach(area => {
//         area.classList.remove('active');
//     });

//     // 移除所有菜单项的激活状态
//     document.querySelectorAll('.menu-item').forEach(item => {
//         item.classList.remove('active');
//     });

//     // 显示指定内容区域
//     const targetArea = document.getElementById(contentId);
//     if (targetArea) {
//         targetArea.classList.add('active');
//         currentPage = contentId;

//         // 激活对应菜单项 - 修复快速操作按钮问题
//         const menuItem = document.querySelector(`[onclick*="${contentId}"]`);
//         if (menuItem && menuItem.classList.contains('menu-item')) {
//             menuItem.classList.add('active');
//         }

//         // 根据不同页面加载相应数据
//         loadPageData(contentId);
//     }
// }

// 加载页面数据
function loadPageData(pageId) {
    switch(pageId) {
        case 'dashboard':
            if (typeof DashboardModule !== 'undefined') {
                DashboardModule.loadStatistics();
            }
            // 根据用户角色控制快速操作按钮的显示/隐藏
            setTimeout(() => {
                if (userInfo && userInfo.userType === '1') {
                    // 校领导：只显示测评关系和分数查询
                    hideAdminQuickActions();
                } else {
                    // 管理员：显示所有快速操作
                    showAllQuickActions();
                }
            }, 100);
            break;
        case 'dept-info-management':
            if (typeof BaseInfoModule !== 'undefined') {
                BaseInfoModule.loadDeptList();
            }
            break;
        case 'teacher-info-management':
            if (typeof BaseInfoModule !== 'undefined') {
                BaseInfoModule.init(); // 先初始化，加载部门下拉框数据
                BaseInfoModule.loadTeacherList();
            }
            break;
        case 'position-type-management':
            if (typeof BaseInfoModule !== 'undefined') {
                BaseInfoModule.loadPositionTypeList();
            }
            break;
        case 'teacher-position-management':
            if (typeof BaseInfoModule !== 'undefined') {
                BaseInfoModule.init(); // 先初始化，加载岗位下拉框数据
                BaseInfoModule.loadTeacherPositionList();
            }
            break;
        case 'evaluation-content-management':
            if (typeof EvaluationContentModule !== 'undefined') {
                EvaluationContentModule.init();
            }
            break;
        case 'evaluation-type-management':
            if (typeof EvaluationContentModule !== 'undefined') {
                EvaluationContentModule.loadEvaluationTypeList();
            }
            break;
        case 'evaluation-relation-management':
            if (typeof EvaluationRelationModule !== 'undefined') {
                EvaluationRelationModule.init();
            }
            // 对于测评关系管理页面，需要再次检查权限控制
            setTimeout(() => {
                if (userInfo && userInfo.userType === '1') {
                    hideRelationGenerationForSchoolLeader();
                }
            }, 100);
            break;
        case 'evaluation-score-management':
            if (typeof EvaluationScoreModule !== 'undefined') {
                EvaluationScoreModule.init();
            }
            // 对于测评分数页面，需要再次检查权限控制
            setTimeout(() => {
                if (userInfo && userInfo.userType === '1') {
                    hideCalculationTabForSchoolLeader();
                }
            }, 100);
            break;
        case 'data-export':
            // 数据导出页面不需要特别的初始化
            break;
        default:
            break;
    }
}

// 通用分页函数
function createPagination(containerId, totalPages, currentPage, onPageChange) {
    const container = document.getElementById(containerId);
    if (!container) return;

    container.innerHTML = '';

    // 上一页按钮
    const prevBtn = document.createElement('button');
    prevBtn.textContent = '上一页';
    prevBtn.className = 'pagination-btn';
    prevBtn.disabled = currentPage <= 1;
    prevBtn.onclick = () => {
        if (currentPage > 1) {
            onPageChange(currentPage - 1);
        }
    };
    container.appendChild(prevBtn);

    // 页码按钮
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);

    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.textContent = i;
        pageBtn.className = 'pagination-btn' + (i === currentPage ? ' active' : '');
        pageBtn.onclick = () => onPageChange(i);
        container.appendChild(pageBtn);
    }

    // 下一页按钮
    const nextBtn = document.createElement('button');
    nextBtn.textContent = '下一页';
    nextBtn.className = 'pagination-btn';
    nextBtn.disabled = currentPage >= totalPages;
    nextBtn.onclick = () => {
        if (currentPage < totalPages) {
            onPageChange(currentPage + 1);
        }
    };
    container.appendChild(nextBtn);
}

// 通用API请求
function apiRequest(url, options = {}) {
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json'
        }
    };
    
    return fetch(globalConfig.apiBase + url, { ...defaultOptions, ...options });
}

// 通用错误处理
function handleApiError(error, context = '') {
    console.error(`${context}失败:`, error);
    alert('网络错误，请稍后重试');
}

// 通用成功提示
function showSuccess(message) {
    alert(message);
}

// 通用确认对话框
function confirmAction(message) {
    return confirm(message);
}

// 导出工具函数到全局
window.CommonModule = {
    showModal,
    closeModal,
    // showContent, // 已移至index.html中重新实现以支持组件化
    createPagination,
    apiRequest,
    handleApiError,
    showSuccess,
    confirmAction,
    globalConfig
}; 

// 显示所有菜单（管理员权限）
function showAllMenus() {
    // 显示所有菜单项
    document.querySelectorAll('.menu-item').forEach(item => {
        item.style.display = 'block';
    });
    
    // 显示所有菜单组
    document.querySelectorAll('.menu-group').forEach(group => {
        group.style.display = 'block';
    });
}

// 通用提示函数
function showAlert(message, type = 'info') {
    // 创建提示框
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type}`;
    alertDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'error' ? '#f56565' : type === 'warning' ? '#ed8936' : '#4299e1'};
        color: white;
        padding: 12px 20px;
        border-radius: 6px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        z-index: 10000;
        font-size: 14px;
        min-width: 200px;
        opacity: 0;
        transform: translateX(100%);
        transition: all 0.3s ease;
    `;
    alertDiv.textContent = message;
    
    document.body.appendChild(alertDiv);
    
    // 显示动画
    setTimeout(() => {
        alertDiv.style.opacity = '1';
        alertDiv.style.transform = 'translateX(0)';
    }, 10);
    
    // 自动移除
    setTimeout(() => {
        alertDiv.style.opacity = '0';
        alertDiv.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.parentNode.removeChild(alertDiv);
            }
        }, 300);
    }, 3000);
} 